import { showToast } from './util.js'
import { baseurl } from './config.js'

function service(options = {}) {
    const userinfo = uni.getStorageSync('zzk:user')
    const tm = Math.round(new Date().getTime() / 1000).toString()
    
    // 配置请求头
    options.header = {
        'content-type' : "application/json",
        'Timestamp' : tm
    }
    // 设置主账号id
    const urls = ['/njnzzs/token', '/njnzzs/merchant/list']
    if (userinfo.merchantId && !urls.includes(options.url)) {
        options.header.merchantId = userinfo.merchantId
    }
    
    // 设置请求地址
    options.url = `${baseurl}${options.url}`
    
    if (userinfo && userinfo.token) {
        options.header.Authorization = userinfo.token
    }
    
    return new Promise((resolve, reject) => {
        // 成功
        options.success = response => {
            const res = response.data
            const code = Number(res.code)
            if (code === 0) {
                resolve(res.data)
            } else {
                showToast(res.errorMsg)
                reject(res.errorMsg)
            }
        }
        // 失败
        options.fail = err => {
            reject(err)
        }
        uni.request(options)
    })
}

export default service